// Copyright 2007 the original author or authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package lichen.components;

import java.util.List;

import lichen.components.base.AbstractLayout;
import lichen.entities.user.User;
import lichen.pages.base.MenuPage;
import lichen.services.menu.Menu;
import lichen.services.user.impl.UserServiceImpl;

import org.apache.tapestry.ComponentResources;
import org.apache.tapestry.annotations.Component;
import org.apache.tapestry.annotations.Inject;
import org.apache.tapestry.corelib.components.Loop;
import org.apache.tapestry.corelib.components.PageLink;
import org.apache.tapestry.services.Cookies;
import org.hibernate.Session;

/**
 * 论坛的整体的布局
 * @author jcai
 * @version $Revision: 7 $
 * @since 0.0.2
 */
public class Layout extends AbstractLayout{
	
	@Inject
	private ComponentResources componentResources;
	
	@SuppressWarnings("unused")
	@Component(parameters={"source=menus","value=menu"})
	private Loop menuLoop;
	
	@Inject
	private Cookies cookies;
	@Inject
	private Session session;
	/**
	 * 循环使用menu变量
	 */
	private Menu menu;
	
	@SuppressWarnings("unused")
	@Component(parameters={"page=prop:menu.pagePath","context=menu.pageContext"})
	private PageLink menuPageLink;
	/**
	 * @return Returns the menu.
	 */
	public Menu getMenu() {
		return menu;
	}
	
	/**
	 * @param menu The menu to set.
	 */
	public void setMenu(Menu menu) {
		this.menu = menu;
	}
	public List<Menu> getMenus(){
		org.apache.tapestry.runtime.Component page = componentResources.getPage();
		if(MenuPage.class.isInstance(page)){
			return ((MenuPage) page).contributeMenus();
		}else{
			return null;
		}
	}
	/**
	 * 是否登录.
	 * @return 是否登录.
	 */
	public boolean isLogin(){
		String userId = cookies.readCookieValue(UserServiceImpl.LICHEN_USER_ID_COOKIE_NAME);
		if(userId != null){
			 User user = (User) session.get(User.class, userId);
			 if(user==null){
				 cookies.removeCookieValue(UserServiceImpl.LICHEN_USER_ID_COOKIE_NAME);
			 }
			 return user!=null;
		}
		return false;
	}
	public User getUser(){
		if(isLogin()){
			String userId = cookies.readCookieValue(UserServiceImpl.LICHEN_USER_ID_COOKIE_NAME);
			User user = (User) session.get(User.class, userId);
			return user;
		}else{
			throw new RuntimeException("invalid request");
		}
	}

	
}
